package com.quzi.kettle.activitise.main;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.activitise.added.TipVoiceActivity;
import com.quzi.kettle.bean.Appoint;
import com.quzi.kettle.service.AlarmService;
import com.quzi.kettle.utils.DateUtils;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.utils.TipvoiceUtil;
import com.quzi.kettle.view.MNumberPicker;
import com.quzi.kettle.view.MNumberReceive;
import com.quzi.kettle.view.TitleBarHandler;
import com.quzi.kettle.view.TitleBarView;

public class XiGuanActivity extends BaseActivity implements MNumberReceive {

	private TitleBarView titleView;
	private ListView timerlist;
	private List<Appoint> appointList = new ArrayList<Appoint>();
	private MNumberPicker mNumberPicker;
	private dataListAdapter adapter;

	private CheckBox remide;
	private RelativeLayout rela_xiguan_tipvoice;
	private TextView tv_xiguan_whaovoice;
	boolean flag = false;
	boolean numberflag = false;
	int numberposition = -1;
	// 定义AlarmManager对象
	AlarmManager aManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_xiguan);
		timerlist = (ListView) findViewById(R.id.timerlist);
		adapter = new dataListAdapter(appointList);
		timerlist.setAdapter(adapter);
		remide = (CheckBox) findViewById(R.id.remide);

		aManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
		// 指定启动ChangeService组件
		Intent intent = new Intent(XiGuanActivity.this, AlarmService.class);
		// 创建PendingIntent对象
		final PendingIntent pi = PendingIntent.getService(XiGuanActivity.this,
				0, intent, 0);

		remide.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				MSharePerference.getInstance(getApplicationContext())
						.updateBoolean("remide", arg1);
				flag = arg1;
				if (!arg1) {
					appointList = getAllAppoint();
					for (int i = 0; i < appointList.size(); i++) {
						updateAppoint(i, appointList.get(i).getTitle(), false,
								false);

					}
					appointList = getAllAppoint();
					adapter.notifyData(appointList);
					aManager.cancel(pi);

				} else {
					aManager.setRepeating(AlarmManager.RTC_WAKEUP, 0,
							30 * 1000, pi);
				}

			}
		});
		boolean flag = MSharePerference.getInstance(getApplicationContext())
				.getBoolean("remide");
		remide.setChecked(flag);

		initTitleBar();
		updateData();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initVoiceTip();
	}

	private void initVoiceTip() {

		tv_xiguan_whaovoice = (TextView) findViewById(R.id.tv_xiguan_whaovoice);
		if (TipvoiceUtil.getVoiceName(getApplicationContext()).equals("")) {
			tv_xiguan_whaovoice.setText(getResources().getString(
					R.string.as_usual));
		} else {
			tv_xiguan_whaovoice.setText(TipvoiceUtil
					.getVoiceName(getApplicationContext()));
		}
		rela_xiguan_tipvoice = (RelativeLayout) findViewById(R.id.rela_xiguan_tipvoice);
		rela_xiguan_tipvoice.setOnClickListener(this);

	}

	private void updateData() {
		// TODO Auto-generated method stub
		appointList = getAllAppoint();

		for (int i = 0; i < appointList.size(); i++) {
			Log.d("appoint", "appoint = " + appointList.get(i).toString());
		}

		adapter.notifyData(appointList);
	}

	@Override
	protected void initTitleBar() {
		// TODO Auto-generated method stub
		super.initTitleBar();
		titleView = (TitleBarView) findViewById(R.id.titleview);
		titleView.setTitle(getResources().getString(R.string.xiguan));
		titleView.setRightIncon(R.drawable.plus);
		titleView.setTitleBarClickListener(new TitleBarHandler() {

			@Override
			public void ClickRight() {
				// 弹出Dialog
				numberflag = false;
				int height = 600;
				if (mNumberPicker == null) {
					mNumberPicker = new MNumberPicker(getApplicationContext(),
							height);
					Display display = getWindowManager().getDefaultDisplay();
					LayoutInflater inflater = (LayoutInflater) XiGuanActivity.this
							.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					ViewGroup pickerView = (ViewGroup) inflater.inflate(
							R.layout.pop_menu, null);
					mNumberPicker.initNumberPicker(display,
							getLayoutInflater(), pickerView);
					mNumberPicker.setNumberReceive(XiGuanActivity.this);

					mNumberPicker.setTitle("选择定时时间");
				}
				mNumberPicker.setCancleButtonText("");
				mNumberPicker.showNumberPicker(MNumberPicker.PICKER_TYPE_TIME);
				mNumberPicker.setCurrTimeValue(DateUtils.getCurrHour(),
						DateUtils.getCurrMinute());
			}

			@Override
			public void ClickLeft() {
				finish();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rela_xiguan_tipvoice:
			nextActivity(TipVoiceActivity.class);
			break;

		default:
			break;
		}

	}

	/** 获取所有的数据 */
	public List<Appoint> getAllAppoint() {
		String appoints = MSharePerference.getInstance(getApplicationContext())
				.get("appoint");
		List<Appoint> list = new ArrayList<Appoint>();
		if (!appoints.isEmpty()) {
			String[] myappoint = appoints.split(",");
			for (int i = 0; i < myappoint.length; i++) {
				Log.d("appoint", "appoint = " + myappoint[i]);
				String[] mapp = myappoint[i].split("!");
				String title = mapp[0];
				boolean status = mapp[1].equals("true") ? true : false;
				Appoint appoint = new Appoint(title, status);
				list.add(appoint);
			}
		}
		return list;
	}

	/** 更新数据列表 */
	public List<Appoint> updateAppoint(int index, String time, boolean setTo,
			boolean isDelete) {
		String appoints = MSharePerference.getInstance(getApplicationContext())
				.get("appoint");
		List<Appoint> list = new ArrayList<Appoint>();
		if (!appoints.isEmpty()) {
			String[] myappoint = appoints.split(",");
			if (index > myappoint.length) {
				return null;
			}
			StringBuilder sb = new StringBuilder();
			if (!isDelete) {
				myappoint[index] = time + "!" + setTo;
				for (int i = 0; i < myappoint.length; i++) {
					sb.append(myappoint[i]);
					sb.append(",");
				}
			} else {
				for (int i = 0; i < myappoint.length; i++) {
					if (i == index) {
						continue;
					}
					sb.append(myappoint[i]);
					sb.append(",");
				}
			}
			MSharePerference.getInstance(getApplicationContext()).update(
					"appoint", sb.toString());
		}
		return getAllAppoint();
	}

	class dataListAdapter extends BaseAdapter {
		List<Appoint> appointList;

		public dataListAdapter(List<Appoint> list) {
			appointList = list;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return appointList.size();
		}

		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public void notifyData(List<Appoint> list) {
			this.appointList = list;
			notifyDataSetChanged();
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {

			LayoutInflater inflater = getLayoutInflater();
			View row;
			row = inflater.inflate(R.layout.appoint_item, parent, false);
			TextView title;
			CheckBox box = (CheckBox) row.findViewById(R.id.checked);

			box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0,
						boolean isChecked) {
					updateAppoint(position, appointList.get(position)
							.getTitle(), isChecked, false);
				}
			});

			box.setChecked(appointList.get(position).isStatus());
			title = (TextView) row.findViewById(R.id.name);
			title.setText(appointList.get(position).getTitle());
			row.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View view) {
					numberflag = true;
					numberposition = position;
					int height = 600;
					if (mNumberPicker == null) {
						mNumberPicker = new MNumberPicker(
								getApplicationContext(), height);
						Display display = getWindowManager()
								.getDefaultDisplay();
						LayoutInflater inflater = (LayoutInflater) XiGuanActivity.this
								.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						ViewGroup pickerView = (ViewGroup) inflater.inflate(
								R.layout.pop_menu, null);
						mNumberPicker.initNumberPicker(display,
								getLayoutInflater(), pickerView);
						mNumberPicker.setNumberReceive(XiGuanActivity.this);

						mNumberPicker.setTitle("选择定时时间");
					}
					mNumberPicker.setCancleButtonText("");
					mNumberPicker
							.showNumberPicker(MNumberPicker.PICKER_TYPE_TIME);
					mNumberPicker.setCurrTimeValue(
							Integer.parseInt(appointList.get(position)
									.getTitle().split(":")[0]),
							Integer.parseInt(appointList.get(position)
									.getTitle().split(":")[1]));

				}
			});
			row.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View view) {
					// TODO Auto-generated method stub
					final String targetTime = ((TextView) view
							.findViewById(R.id.name)).getText().toString();
					final Dialog alertDialog = new AlertDialog.Builder(
							XiGuanActivity.this).setTitle("确认删除改记录？")
							.setIcon(R.drawable.ic_launcher)
							.setPositiveButton("确认", new OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
									// TODO Auto-generated method stub
									for (int i = 0; i < appointList.size(); i++) {
										if ((targetTime.equals(appointList.get(
												i).getTitle()))) {
											appointList.remove(i);
											updateAppoint(i, "00:00", false,
													true);
											adapter.notifyDataSetChanged();
										}
									}
								}
							}).setNegativeButton("取消", new OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,
										int arg1) {
								}
							}).create();
					alertDialog.show();
					return false;
				}
			});

			return (row);
		}
	}

	@Override
	public boolean checkCanDiss(int type, Object... objs) {
		return true;
	}

	@Override
	public void updateDate(int year, int month, int day) {

	}

	@Override
	public void updateTime(int hour, int minte) {
		if (!numberflag) {
			StringBuilder sb = new StringBuilder();
			if (hour < 10) {
				sb.append("0");
			}
			sb.append(hour + ":");
			if (minte < 10) {
				sb.append("0");
			}
			sb.append(minte);
			Appoint currAppoint = new Appoint(sb.toString(), flag);

			String appoint = MSharePerference.getInstance(
					getApplicationContext()).get("appoint");
			MSharePerference.getInstance(getApplicationContext()).update(
					"appoint", appoint + currAppoint.toString());

		} else {
			numberflag = false;
			if (numberposition == -1) {

			} else {
				StringBuilder sb = new StringBuilder();
				if (hour < 10) {
					sb.append("0");
				}
				sb.append(hour + ":");
				if (minte < 10) {
					sb.append("0");
				}
				sb.append(minte);
				updateAppoint(numberposition, sb.toString(),
						appointList.get(numberposition).isStatus(), false);
				numberposition = -1;
			}

		}
		updateData();

	}

	@Override
	public void updateTime12(int ampm, int hour, int minte) {
		// TODO Auto-generated method stub

	}

	@Override
	public void leftBtnClick() {
		// TODO Auto-generated method stub

	}

	// private void setAlarm() {
	// // 获取AlarmManager系统服务
	// AlarmManager manager = (AlarmManager)
	// this.getSystemService(Context.ALARM_SERVICE);
	//
	// // 包装需要执行Service的Intent
	// Intent intent = new Intent(this, cls);
	// intent.setAction(action);
	// PendingIntent pendingIntent = PendingIntent.getService(context, 0,
	// intent, PendingIntent.FLAG_UPDATE_CURRENT);
	//
	// // 触发服务的起始时间
	// long triggerAtTime = SystemClock.elapsedRealtime();
	//
	// // 使用AlarmManger的setRepeating方法设置定期执行的时间间隔（seconds秒）和需要执行的Service
	// manager.setRepeating(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
	// seconds * 1000, pendingIntent);
	// }

}
